using B.S.Medical.Api.Read.Application.Command.Home;
using B.S.Medical.Api.Read.DTOS;
using B.S.Medical.Domain.Medical;
using B.S.Medical.Domain.Doctor;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Medical.Api.Read.Application.Handler.Home
{
    public class GetHotDoctorsHandler : IRequestHandler<GetHotDoctorsCommand, ApiResult<List<HotDoctorDto>>>
    {
        private readonly IBaseRepository<RegisterModel> _registerRepo;
        private readonly IBaseRepository<DoctorModel> _doctorRepo;

        public GetHotDoctorsHandler(
            IBaseRepository<RegisterModel> registerRepo,
            IBaseRepository<DoctorModel> doctorRepo)
        {
            _registerRepo = registerRepo;
            _doctorRepo = doctorRepo;
        }

        public async Task<ApiResult<List<HotDoctorDto>>> Handle(GetHotDoctorsCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<List<HotDoctorDto>>();
            try
            {
                // 统计各医生的预约人数
                var doctorStats = _registerRepo.GetAll()
                    .Where(x => !x.IsDeleted)
                    .Join(_doctorRepo.GetAll().Where(d => !d.IsDeleted),
                          register => register.DoctorId,
                          doctor => doctor.Id,
                          (register, doctor) => new { register, doctor })
                    .GroupBy(x => new { x.doctor.Id, x.doctor.DoctorName })
                    .Select(g => new
                    {
                        DoctorId = g.Key.Id,
                        DoctorName = g.Key.DoctorName,
                        AppointmentCount = g.Count()
                    })
                    .OrderByDescending(x => x.AppointmentCount)
                    .Take(request.Limit)
                    .ToList();

                var result = new List<HotDoctorDto>();
                int rank = 1;

                foreach (var stat in doctorStats)
                {
                    result.Add(new HotDoctorDto
                    {
                        Rank = rank++,
                        DoctorName = stat.DoctorName,
                        AppointmentCount = stat.AppointmentCount
                    });
                }

                res.Data = result;
                res.Msg = "获取热门医生数据成功!";
                res.Code = ApiEnum.Success;
            }
            catch (Exception ex)
            {
                res.Data = null;
                res.Msg = "获取热门医生数据异常：" + ex.Message;
                res.Code = ApiEnum.Error;
            }
            return await Task.FromResult(res);
        }
    }
} 